package com.fingard.dsp.bank.directbank.wzcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

/**
 * 温州银行明细查询
 */
public class WZCB01Transaction extends WZCB01Base implements ITransaction {
    /**
     * 历史明细
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo ="";
        try{
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                boolean isPage=true;//是否进行下一页查询
                int page=0;//页码
                int readNum=0;//已查询数
                while (isPage){
                    //拼接请求报文体
                    WZCB01Header header = new WZCB01Header();
                    header.txCode="E103";//SQEPay.103.01.01
                    header.orderNo = getQryTransID();
                    XmlTextWriter xmlReq = new XmlTextWriter();
                    writeReqHeader(xmlReq,header);
                    XElement body =new XElement("Body","");
                    body.addChild(new XElement("BusCode","1"));//保留域填 ‘1’
                    body.addChild(new XElement("PayAcctNo",p_req7516.actNum));//账号
                    body.addChild(new XElement("PayAcctSeqno","0"));//必填 0 （保留为接口扩展用）
                    body.addChild(new XElement("StartDate",Format.Date10Format.format(tmpCalendarFrom.getTime())));//起始日期
                    body.addChild(new XElement("EndDate",Format.Date10Format.format(tmpClndrStepTo.getTime())));//终止日期
                    body.addChild(new XElement("TotalCnt","30"));//每页笔数
                    body.addChild(new XElement("StartSeqno",page+""));//起始页(如果传0，表示从第一页开始)
                    xmlReq.writeXElement(body);
                    xmlReq.writeEndDocument();
                    //组装head
                    String head=getHead("E103","SQEPay.103.01.01");
                    //发送请求报文
                    String[] resutlt = sendToBank(xmlReq.toXmlString(),head);
                    //处理响应报文
                    if(resutlt[0].length()==0){
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1], tmpSbMsg);
                        if(tmpBkReader!=null) {
                            String respCode = tmpBkReader.getFirstText("/Response/Head/RefuseCode");
                            String respInfo = tmpBkReader.getFirstText("/Response/Head/RefuseReason");
                            if ("0000".equals(respCode)) {//交易成功
                                String actNum=tmpBkReader.getFirstText("/Response/Body/PayAcctNo");//查询账号
                                String actCur=convertCurToATS(tmpBkReader.getFirstText("/Response/Body/CurCode"));//查询币种
                                int totalNum=Integer.parseInt(tmpBkReader.getFirstText("/Response/Body/EndSeqno"));//查询总笔数
                                int pageNum=Integer.parseInt(tmpBkReader.getFirstText("/Response/Body/MerGoodsNum"));//本页笔数
                                readNum+=pageNum;
                                if(totalNum<=readNum){//查询数超过总数，不再进行下一页查询
                                    isPage=false;
                                }else {
                                    page++;
                                }
                                if(totalNum>0){
                                    while (tmpBkReader.read("/Response/Body/QryList")){
                                        XElement readXElement = tmpBkReader.readedXElement;
                                        RetAtsTransDetail detail = new RetAtsTransDetail();
                                        detail.actArea=p_req7516.actArea;
                                        detail.actNum = actNum;
                                        detail.tranDate =readXElement.getSingleTextNotNull("TransDate").trim();
                                        detail.valueDate = detail.tranDate;
                                        String times=readXElement.getSingleTextNotNull("TransTime").trim();
                                        detail.tranTime = detail.valueDate+ " " + times.substring(0,2)+":"+times.substring(2,4)+":"+times.substring(4,6);
                                        detail.cur = actCur;//币种
                                        detail.accBal = readXElement.getSingleTextNotNull("PayAcctBal");//账户余额
                                        String note = readXElement.getSingleTextNotNull("AbsInfo").trim();
                                        detail.usage = note;
                                        detail.abstr = pickupAbstr(note);
                                        detail.originator = readXElement.getSingleTextNotNull("VouNo").trim();//银行流水号
                                        detail.recAccNum = readXElement.getSingleTextNotNull("RcvAcctNo").trim();
                                        detail.recAccName = readXElement.getSingleTextNotNull("RcvAcctName").trim();
                                        detail.recAccBank = readXElement.getSingleTextNotNull("RcvSysName").trim();
                                        String transAmt=readXElement.getSingleTextNotNull("TransAmt");//交易发生额
                                        String dcFlag=readXElement.getSingleTextNotNull("DcFlag");//借贷标志 1：借方 2：贷方
                                        if("1".equals(dcFlag)){
                                            if(transAmt.startsWith("-")){
                                                detail.cdFlag="2";
                                                detail.tranAmt=transAmt.substring(1);
                                            }else {
                                                detail.cdFlag="1";
                                                detail.tranAmt=transAmt;
                                            }
                                        }else if("2".equals(dcFlag)){
                                            if(transAmt.startsWith("-")){
                                                detail.cdFlag="1";
                                                detail.tranAmt=transAmt.substring(1);
                                            }else {
                                                detail.cdFlag="2";
                                                detail.tranAmt=transAmt;
                                            }
                                        }
                                        retAtsTrans.writeRetDetail(detail);
                                    }
                                }
                            }else if("0003".equals(respCode)){
                                tmpRespInfo = respInfo;
                                break;
                            } else {//查询异常
                                tmpRespCode = "-1";
                                tmpRespInfo = respInfo;
                                break;
                            }
                        }else{
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    }else{
                        tmpRespCode = "-1";
                        tmpRespInfo = resutlt[1];
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:"+ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        }else if(retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
